package com.zhaolixiang.camera02

import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
import android.view.View
import java.util.jar.Attributes

/**
 * Created by Administrator on 2017/12/27.
 * 可以调整到指定的宽高比的TextureView
 */
class AutoFitTextureView(context:Context,attributes: AttributeSet):TextureView (context,attributes){
    private var mRatioWidth = 0
    private var mRatioHeight = 0
    /**
     * 设置此视图的宽高比。 视图的大小将根据参数计算的比率进行测量。
     * 请注意，参数的实际大小并不重要，即调用setAspectRatio（2,3）和setAspectRatio（4,6）的结果相同。
     *
     * @param width  相对水平尺寸
     * @param height 相对垂直尺寸
     */
    fun setAspectRatio(width: Int, height: Int) {
        if (width < 0 || height < 0) {
            throw IllegalArgumentException("Size cannot be negative.")
        }
        mRatioWidth = width
        mRatioHeight = height
        requestLayout()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = View.MeasureSpec.getSize(widthMeasureSpec)
        val height = View.MeasureSpec.getSize(heightMeasureSpec)
        if (0 == mRatioWidth || 0 == mRatioHeight) {
            setMeasuredDimension(width, height)
        } else {
            if (width < height * mRatioWidth / mRatioHeight) {
                setMeasuredDimension(width, width * mRatioHeight / mRatioWidth)
            } else {
                setMeasuredDimension(height * mRatioWidth / mRatioHeight, height)
            }
        }
    }
}